<template>
  <div v-if="isVisible" class="back-to-top text-main" @click="scrollToTop">TOP</div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, onBeforeUnmount } from 'vue'

export default defineComponent({
  setup() {
    const isVisible = ref(false)

    const checkScroll = () => {
      isVisible.value = window.scrollY > 1
    }

    const scrollToTop = () => {
      window.scrollTo({ top: 0, behavior: 'smooth' })
    }

    onMounted(() => {
      window.addEventListener('scroll', checkScroll)
    })

    onBeforeUnmount(() => {
      window.removeEventListener('scroll', checkScroll)
    })

    return {
      isVisible,
      scrollToTop
    }
  }
})
</script>

<style scoped>
.back-to-top {
  position: fixed;
  bottom: 20px;
  right: 20px;
  width: 40px;
  height: 40px;
  background-color: #007bff;
  color: white;
  text-align: center;
  border-radius: 50%;
  cursor: pointer;
  font-size: 20px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
  transition: opacity 0.3s ease;
}

.back-to-top:hover {
  background-color: #0056b3;
}
</style>
